package io.renren.modules.eas.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import io.renren.modules.eas.entity.EasBasicEduEntity;
import io.renren.modules.eas.entity.EasBasicStuEntity;
import io.renren.modules.eas.entity.EasCommentKeysEntity;
import io.renren.modules.eas.service.EasBasicEduService;
import io.renren.modules.eas.service.EasBasicStuService;
import io.renren.modules.eas.service.EasCommentKeysService;
import jdk.nashorn.internal.objects.annotations.Getter;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.eas.entity.EasStuCommentsEntity;
import io.renren.modules.eas.service.EasStuCommentsService;

import javax.servlet.http.HttpServletResponse;


/**
 * 学生评语表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2023-09-26 23:32:06
 */
@RestController
@RequestMapping("eas/easstucomments")
public class EasStuCommentsController {
    @Autowired
    private EasStuCommentsService easStuCommentsService;
    @Autowired
    private EasCommentKeysService easCommentKeysService;
    @Autowired
    private EasBasicStuService easBasicStuService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("eas:easstucomments:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = easStuCommentsService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("eas:easstucomments:info")
    public R info(@PathVariable("id") Long id) {
        EasStuCommentsEntity easStuComments = easStuCommentsService.getById(id);
        List<Integer> edu1 = Arrays.stream(easStuComments.getEdu1Ids().split(","))
                .filter(StringUtils::hasLength)
                .map(Integer::parseInt).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(edu1)){
            List<EasCommentKeysEntity> easCommentKeysEntities = easCommentKeysService.listByIds(edu1);
            easStuComments.setEdu1Keys(easCommentKeysEntities);
        }
        List<Integer> edu2 = Arrays.stream(easStuComments.getEdu2Ids().split(","))
                .filter(StringUtils::hasLength)
                .map(Integer::parseInt).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(edu2)){
            List<EasCommentKeysEntity> easCommentKeysEntities = easCommentKeysService.listByIds(edu2);
            easStuComments.setEdu2Keys(easCommentKeysEntities);
        }
        List<Integer> edu3 = Arrays.stream(easStuComments.getEdu3Ids().split(","))
                .filter(StringUtils::hasLength)
                .map(Integer::parseInt).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(edu3)){
            List<EasCommentKeysEntity> easCommentKeysEntities = easCommentKeysService.listByIds(edu3);
            easStuComments.setEdu3Keys(easCommentKeysEntities);
        }
        List<Integer> edu4 = Arrays.stream(easStuComments.getEdu4Ids().split(","))
                .filter(StringUtils::hasLength)
                .map(Integer::parseInt).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(edu4)){
            List<EasCommentKeysEntity> easCommentKeysEntities = easCommentKeysService.listByIds(edu4);
            easStuComments.setEdu4Keys(easCommentKeysEntities);
        }
        List<Integer> edu5 = Arrays.stream(easStuComments.getEdu5Ids().split(","))
                .filter(StringUtils::hasLength)
                .map(Integer::parseInt).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(edu5)){
            List<EasCommentKeysEntity> easCommentKeysEntities = easCommentKeysService.listByIds(edu5);
            easStuComments.setEdu5Keys(easCommentKeysEntities);
        }
        return R.ok().put("easStuComments", easStuComments);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("eas:easstucomments:save")
    public R save(@RequestBody EasStuCommentsEntity easStuComments) {
        easStuCommentsService.save(easStuComments);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("eas:easstucomments:update")
    public R update(@RequestBody EasStuCommentsEntity easStuComments) {
        easStuCommentsService.updateById(easStuComments);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("eas:easstucomments:delete")
    public R delete(@RequestBody Long[] ids) {
        easStuCommentsService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 添加内置关键字
     */
    @RequestMapping("/addCommentKey")
    public R addCommentKey(@RequestBody EasStuCommentsEntity entity) {
        easStuCommentsService.updateById(entity);
        return R.ok();
    }


    @RequestMapping("/getComment")
    public R getComment(@RequestBody Map<String,Object> params){
        Object commentNum =  params.get("commentNum");
        String keywords = (String) params.get("keywords");
        if (ObjectUtils.isEmpty(keywords)){
            return R.error("关键词不能为空");
        }
        String res = getResult("https://test123456.kooldns.cn:443",
                "按照下述关键词:"+ keywords + "给出一段"+ commentNum
                        + "字以下的学生评语");

        if (res.contains("请求失败") || res.contains("请求发生异常")){
            System.out.println(res);
            return R.error(res);
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        res = jsonObject.getString("response");
        easStuCommentsService.lambdaUpdate()
                .set(EasStuCommentsEntity::getComment,res)
                .eq(EasStuCommentsEntity::getId,params.get("id"))
                .update();
        //80-90 随机数
        int score = (int) (Math.random() * 10 + 80);
        return R.ok().put("res",res).put("score",score);

    }


    public String getResult(String url, String prompt)
    {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        try {
            // 设置请求体数据
            StringEntity requestEntity = new StringEntity("{\"prompt\":\"" +prompt + "\",\"history\":[],\"max_length\":500,\"top_p\":0.5,\"temperature\":0.5}",
                    ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);

            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString(responseEntity);

            // 处理响应数据
            if (response.getStatusLine().getStatusCode() == 200) {
                return responseBody;
            } else {
                return "请求失败，状态码：" + response.getStatusLine().getStatusCode();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "请求发生异常：" + e.getMessage();
        }
    }


    @RequestMapping("/export")
    public void getComment(HttpServletResponse response) throws IOException {
        List<EasStuCommentsEntity> list = easStuCommentsService.list();

        ArrayList<DemoData> demoData1 = new ArrayList<>();
        for (EasStuCommentsEntity easStuCommentsEntity : list) {
            EasBasicStuEntity eduEntity = easBasicStuService.getById(easStuCommentsEntity.getStudentId());
            DemoData demoData = new DemoData();
            demoData.setString(eduEntity.getName());
            demoData.setDate(easStuCommentsEntity.getComment());
            demoData1.add(demoData);
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("学生评语", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DemoData.class)
                .sheet("学生评语")
                .doWrite(demoData1);
    }


    @Data
    public class DemoData {
        @ExcelProperty("姓名")
        private String string;
        @ExcelProperty("评语")
        private String date;
    }

}
